package com.ruoyi.web.api;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ChatUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.ChatMessage;
import com.ruoyi.system.domain.ChatRequire;
import com.ruoyi.system.domain.vo.ChatRequireReqVo;
import com.ruoyi.system.domain.vo.MessageVo;
import com.ruoyi.system.service.IChatMessageService;
import com.ruoyi.system.service.IChatRequireService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户会话信息-对外API接口请求处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/api/chat/message")
public class ApiChatMessageController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(ApiChatMessageController.class);

    @Autowired
    private IChatMessageService chatMessageService;
    @Autowired
    private IChatRequireService chatRequireService;
    private final static String BASE_URL = "http://120.77.181.233:3020/api";
    private final static String API_KEY = "fastgpt-9AjITfj3hYiL3Z23bicyMRmDBCwY44bLuQdeZOxkV1YQeQcLbSr4agz";

    /**
     * 获取【BankChat会话消息】信息
     */
    @GetMapping(value = "/{id}")
    public String getById(@PathVariable("id") String id, HttpServletResponse response) {
        ChatMessage chatMessage = chatMessageService.selectChatMessageByParentId(id);
        if (null != chatMessage && StringUtils.isNotEmpty(chatMessage.getContent())) {
            return chatMessage.getContent();
        }
        response.setStatus(HttpStatus.NO_CONTENT);
        return null;
    }

    /**
     * 获取【BankChat会话消息】信息
     */
    @GetMapping(value = "/list")
    public AjaxResult list(@RequestParam(value = "sessionId", required = false) String sessionId, @RequestParam(value = "topicId", required = false) String topicId) {
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setSessionId(sessionId);
        chatMessage.setTopicId(topicId);
        chatMessage.setUserId(hasLoginUser());
        return AjaxResult.success(chatMessageService.selectChatMessageList(chatMessage));
    }

    /**
     * 新增【BankChat会话消息】
     */
    @Log(title = "【BankChat会话消息】", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    public AjaxResult add(@RequestBody ChatMessage chatMessage) {
        chatMessage.setUserId(getUserId());
        chatMessage.setCreateBy(getUsername());
        int count = chatMessageService.insertChatMessage(chatMessage);
        return AjaxResult.success(count);
    }

    @Log(title = "【AI产生商机消息】", businessType = BusinessType.INSERT)
    @PostMapping(value = "/gpt")
    public AjaxResult gpt(@RequestBody ChatRequireReqVo chatRequire) {
        // 调用fast-gpt，分析商机需求，有则保存商机
        if (null == chatRequire) return AjaxResult.error("参数不能为空");

        // 构建请求体
        Map<String, Object> data = new HashMap<>();
        data.put("chatId", "");
        data.put("stream", false);
        data.put("detail", false);
        List<Map<String, String>> messages = new ArrayList<>();
        Map<String, String> userMsg = null;

        List<MessageVo> messageVos = chatRequire.getMessages();
        if (messageVos.isEmpty()) return AjaxResult.success();
        for (MessageVo message : messageVos) {
            // 添加会话消息，去请求fast-gpt
            userMsg = new HashMap<>();
            userMsg.put("role", message.getRole());
            userMsg.put("content", message.getContent());
            messages.add(userMsg);
        }
        data.put("messages", messages);

        // 对于fast-gpt返回的content, 是否能转成JSON，能则解析用户的商机，保存下来，否则不管
        String result = ChatUtils.requestChatScheme(data);
        log.info("ChatAI回复的content内容为：{}", result);
        try {
            if ("false".equalsIgnoreCase(result)) {
                log.info("ChatAI无法解析商机，没有总结出来");
                return AjaxResult.error();
            }
            result = result.replaceAll("'''", "\"");
            result = result.replaceAll("'", "\"");
            result = result.substring(result.indexOf("{"));
            result = result.substring(0, result.lastIndexOf("}") + 1);
            log.info("ChatAI回复的content内容为处理完成之后为：{}", result);
            ChatUtils.Content res = JSON.parseObject(result, ChatUtils.Content.class);

            ChatRequire require = new ChatRequire();
            require.setUserId(getUserId());
            require.setSessionId(chatRequire.getSessionId());
            require.setTopicId(chatRequire.getTopicId());
            require.setTitle(res.getTitle());
            require.setContent(res.getContent());
            require.setTags(org.apache.commons.lang3.StringUtils.join(res.getTags(), ","));
            require.setCreateBy(getUsername());
            return AjaxResult.success(chatRequireService.insertChatRequire(require));
        } catch (Exception e) {
            log.error("ChatAI回复内容Json解析失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }
}
